import { applyDecorators, MethodNotAllowedException, UseInterceptors } from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { MulterOptions } from "@nestjs/platform-express/multer/interfaces/multer-options.interface";

//封装文件类型过滤
export function fileFilter(type: string[]) {
  return (
    req: any,
    file: Express.Multer.File,
    callback: (error: Error | null, acceptFile: boolean) => void
  ) => {
    const check = type.some(t => file.mimetype.includes(t))
    if(!check) {
      callback(new MethodNotAllowedException('文件类型错误'), false)
    } else {
      callback(null, true)
    }
  }

}

//上传文件装饰器
export function LvUpload (filed: string = 'file', options?: MulterOptions) {
  return applyDecorators(
    UseInterceptors(FileInterceptor(filed, options))
  )
}

/**
 * @param {string} field 上传字段
 * @param {string[]} type 文件类型
 * @param {number} fileSize 文件大小
*/
export function LvUploadFile(field: string = 'file', type: string[] = ['image'], fileSize: number = 3) {
  return LvUpload(field, {
    limits: { fieldSize: Math.pow(1024, 2) * fileSize },
    fileFilter: fileFilter(type)
  })
}